/*
 * @Author: lijing
 * @e-mail: 1413979079@qq.com
 * @LastEditors: lijing
 * @Date: 2020-04-30 22:47:48
 * @LastEditTime: 2020-07-04 09:47:09
 * @FilePath: \client\src\http\request.ts
 * @Description: axios的封装
 */
import axios, { AxiosResponse } from "axios";
import urls from "./urls";
import router from "../router/index";
import store from "../store/index";

const instance = axios.create({
  baseURL: urls.baseUrl,
  timeout: 5000,
});

instance.interceptors.request.use((config) => {
  if (store.state.token) {
    config.headers.Authorization = store.state.token;
  }
  return config;
});

instance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    //默认除了2XX之外的都是错误的，就会走这里
    if (error.response) {
      switch (error.response.status) {
        case 401:
          router.replace({
            path: "login",
            query: { redirect: router.currentRoute.fullPath }, // 将跳转的路由path作为参数，登录成功后跳转到该路由
          });
      }
    }
    return Promise.reject(error.response);
  }
);

interface LoginForm {
  username: string;
  password: string;
}

export default {
  login(data: LoginForm): Promise<AxiosResponse<any>> {
    return instance.post(urls.login, data);
  },
  register(data: object): Promise<AxiosResponse<any>> {
    return instance.post(urls.register, data);
  },
  getUserInfo(token: string): Promise<AxiosResponse<any>> {
    return instance.get(urls.user + "/" + token);
  },
  getImages(pageNum: number): Promise<AxiosResponse<any>> {
    return instance.get(urls.images + "?page=" + pageNum);
  },
  getImageById(id: number): Promise<AxiosResponse<any>> {
    return instance.get(urls.image + "/" + id);
  },
  postComment(data: object): Promise<AxiosResponse<any>> {
    return instance.post(urls.comments, data);
  },
  postImage(data: object): Promise<AxiosResponse<any>> {
    return instance.post(urls.images, data);
  },
  timeline(uid: number): Promise<AxiosResponse<any>> {
    return instance.get(urls.timeline + "?uid=" + uid);
  },
  collect(data: object): Promise<AxiosResponse<any>> {
    return instance.post(urls.collect, data);
  },
  cancelCollect(data: object): Promise<AxiosResponse<any>> {
    return instance.delete(urls.collect, {
      params: data,
    });
  },
  getCollections(uid: number): Promise<AxiosResponse<any>> {
    return instance.get(urls.collect + "?uid=" + uid);
  },
  deleteImage(id: number): Promise<AxiosResponse<any>> {
    return instance.delete(urls.image + "/" + id);
  },
};
